﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Model.Entities;
using CSP.Model.DataAccess;
using Microsoft.SharePoint;
using Microsoft.Office;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using CSP.Model.Presenter;
using Microsoft.SharePoint.Administration;

namespace CSP.Model.Model
{
    public class ModelManager : IModelManager
    {
        #region Peeps

        //public List<Peep> GetPeeps(string listName, string siteUrl)
        //{
        //    return SPDataAccess.GetPeeps(listName, siteUrl);
        //}

        public bool PostPeep(Peep peep, string lstName, string siteUrl)
        {
            bool posted = false;
            try
            {
                Dictionary<string, string> item = new Dictionary<string, string>();
                item["Title"] = peep.Title.ToString();
                item["Tweet"] = peep.Title.ToString();
                item["PostedToFB"] = peep.PostedToFB.ToString();
                item["PostedToTwitter"] = peep.PostedToTwitter.ToString();

                posted = SPDataAccess.addPeep(lstName, item);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return posted;
        }

        public void DeleteAllPeeps(string lstName, string siteUrl)
        {
            try
            {
                SPDataAccess.deleteAllItems(lstName, siteUrl);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetCurrentUserImage()
        {
            string userImg = string.Empty;
            string userName = SPContext.Current.Web.CurrentUser.LoginName;
            try
            {
                Microsoft.Office.Server.UserProfiles.UserProfile user = SPDataAccess.getProfileData(userName);


                if (user["PictureURL"].Value == null)
                    userImg = "/_layouts/images/no_pic.gif";
                else
                    userImg = user["PictureURL"].Value.ToString();

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return userImg;
        }

        #endregion

        #region Follower requests
        public List<FollowerRequest> GetFollowerRequests(string listName)
        {
            List<FollowerRequest> followers = new List<FollowerRequest>();
            SPQuery query = new SPQuery();
            string strQuery = String.Format(
            "<Where><Eq><FieldRef Name='IsAllowed'/><Value Type='Text'>{0}</Value></Eq></Where>", "false");
            query.Query = strQuery;
            SPListItemCollection list = SPDataAccess.getList(listName, query);

            foreach (SPListItem item in list)
            {
                followers.Add(FormatFR(item));
            }

            foreach (FollowerRequest fr in followers)
            {
                Microsoft.Office.Server.UserProfiles.UserProfile up = SPDataAccess.getProfileData(fr.FollowerAccount);

                fr.Department = (up["Department"].Value != null ? up["Department"].Value.ToString() : "");
                fr.PictureURL = (up["PictureURL"].Value != null ? up["PictureURL"].Value.ToString() : "/_layouts/images/person.gif");
            }

            return followers;
        }

        public void approveRequest(string listName, string followerId)
        {
            SPDataAccess.addAsColleague(listName, followerId);
        }

        public void rejectRequest(string listName, string followerId)
        {
            SPDataAccess.deleteItem(listName, followerId);
        }
        #endregion

        #region Following

        public List<UserColleague> GetColleagues()
        {
            SPUser currUser = SPContext.Current.Web.CurrentUser;
            List<UserColleague> colleagues = new List<UserColleague>();

            List<Colleague> colls = new List<Colleague>();
            colls = SPDataAccess.getColleagues(currUser.LoginName);

            foreach (Colleague col in colls)
            {
                colleagues.Add(FormatColleague(col));
            }

            return colleagues;
        }

        public void CheckForNewColleagues()
        {
            SPDataAccess.CheckForNewColleagues();
        }

        #endregion

        #region Changes

        public List<UserChange> GetColleagueUpdates()
        {

            return SPDataAccess.GetColleagueUpdates();
        }

        public List<UserChange> GetMyUpdates()
        {
            List<UserChange> changes = SPDataAccess.getMyUpdates();

            return changes;
        }
        #endregion

        #region Private methods
        private List<Peep> StaticPeeps()
        {
            List<Peep> peeps = new List<Peep>();
            peeps.Add(new Peep("Posted a new document: Working with Application Pools", "Marissa Brewster", DateTime.Parse("2009-07-04"), "A day ago", "/_layouts/images/user1.png", false, false));
            peeps.Add(new Peep("Posted a new blog: Deploying to a Farm", "Jennifer Nichols", DateTime.Parse("2009-07-04"), "Two days ago", "/_layouts/images/user2.png", false, false));
            peeps.Add(new Peep("Posted a new document: Exchange 2010 Preview", "Patrick Andrews", DateTime.Parse("2009-07-04"), "Three days ago", "/_layouts/images/user3.png", false, false));

            return peeps;
        }
        private FollowerRequest FormatFR(SPListItem item)
        {
            string follower = string.Empty;
            string followerId = string.Empty;
            string followerAccount = string.Empty;
            bool isAllowed = false;
            SPUser user = null;
            string userAccount = string.Empty;
            string[] userArray = new string[2];

            try
            {
                if (item["Follower"] != null && item["Follower"].ToString().Trim() != string.Empty)
                    userAccount = item["Follower"].ToString();



                userArray = userAccount.Split('#');
                userAccount = userArray[1];

                SPWeb oSPWeb = SPContext.Current.Web;

                try
                {
                    try
                    {
                        user = oSPWeb.AllUsers[userAccount];
                    }
                    catch
                    {
                        user = oSPWeb.AllUsers[GetFieldValueUserLogin(item, "Follower")];
                    }
                }
                catch
                {
                }

                if (user != null)
                {
                    follower = user.Name;
                    followerId = item.ID.ToString();
                    followerAccount = user.LoginName;
                }

                if (item["IsAllowed"] != null && item["IsAllowed"].ToString().Trim() != string.Empty)
                    isAllowed = Convert.ToBoolean(item["IsAllowed"].ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            FollowerRequest fr = new FollowerRequest(follower, followerAccount, followerId, isAllowed);
            fr.Email = user.Email;
            /*
            SPFieldUser spFieldUser = (SPFieldUser)item.Fields.GetField("Follower");
            spFieldUser.Presence = true;
            fr.Presence = spFieldUser.GetFieldValueAsHtml(item["Follower"]);
             * */
            return fr;
        }



        private string GetFieldValueUserLogin(SPListItem item, string fieldName)
        {
            if (item != null)
            {
                SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item[fieldName] as string);
                return userValue.User.LoginName;
            }
            else
            {
                return string.Empty;
            }
        }


        private UserColleague FormatColleague(Colleague col)
        {
            string dep = col.Profile["Department"].Value != null ? col.Profile["Department"].Value.ToString() : "";
            string pic = col.Profile["PictureURL"].Value != null ? col.Profile["PictureURL"].Value.ToString() : "/_layouts/images/no_pic.gif";
            string fname = col.Profile["FirstName"].Value != null ? col.Profile["FirstName"].Value.ToString() : "";
            string lname = col.Profile["LastName"].Value != null ? col.Profile["LastName"].Value.ToString() : "";
            string name = fname + " " + lname;
            string acc = col.Profile.ProfileManager.MySiteHostUrl + "Person.aspx?accountname=" + (col.Profile["AccountName"].Value != null ? col.Profile["AccountName"].Value.ToString() : "");
            bool presence = false;

            UserColleague colleague = new UserColleague(acc, name, dep, pic, presence);
            return colleague;
        }

        #endregion

    }
}
